package com.ncmmall.mall.controller.business.goods;

import com.ncmmall.application.business.goods.GoodsAttributeApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author linxs
 *         商品规格管理
 */
@Controller
@RequestMapping(value = "/mall/goods/attribute")
public class AttributeController {

    private final static Logger logger = LoggerFactory.getLogger(AttributeController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsAttributeApplication attributeApplication;

    @Autowired
    private OperationLogApplication logApplication;

    @Value("${web.domain}")
    private String webDomain;

    /**
     * 商品规格管理列表
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, GoodsAttribute attribute) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from GoodsAttribute u where u.parent is null and u.type = 1 ", params, attribute);
        QueryPage<GoodsAttribute> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GoodsAttribute.class);
        model.addAttribute("page", page).addAttribute("params", attribute);

        return "mall/goods/attribute/list";
    }

    /**
     * 添加规格页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {
        GoodsAttribute attribute = new GoodsAttribute();
        model.addAttribute("_method", "POST").addAttribute("attribute", attribute);

        return "mall/goods/attribute/form";
    }

    /**
     * 添加规格
     *
     * @param nav
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, GoodsAttribute attribute) {

        attribute.setType(1);
        attributeApplication.create(attribute);

        logApplication.eventOfSystem(Securitys.currentUser(), "添加平台规格", Securitys.getIp(request));

        return ImmutableMap.of("status", true);
    }

    /**
     * 删除规格值
     *
     * @param request
     * @param requestWith
     * @param attribute
     * @return
     */
    @RequestMapping(value = "/{id}/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsAttribute attribute) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            attributeApplication.removeAttributeValue(attribute);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除平台规格", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            return ImmutableMap.of("status", false, "message", "该规格已被使用，不允许删除");
        }
    }

    /**
     * 编辑规格页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        GoodsAttribute attribute = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(id), GoodsAttribute.class);

        model.addAttribute("_method", "PUT").addAttribute("attribute", attribute);

        return "mall/goods/attribute/form";
    }


    /**
     * 修改规格
     *
     * @param model
     * @param nav
     * @return
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsAttribute attribute) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            attributeApplication.modify(attribute);
            logApplication.eventOfSystem(Securitys.currentUser(), "修改平台规格", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            return ImmutableMap.of("status", false, "message", "该规格已被使用，不允许删除");
        }
    }

    /**
     * 启用规格
     *
     * @param request
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> enable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsAttribute attribute = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(id), GoodsAttribute.class);

            attributeApplication.enable(attribute);
            logApplication.eventOfMerchant(Securitys.currentUser(), "启用商品规格", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }


    }

    /**
     * 禁用规格
     *
     * @param request
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsAttribute attribute = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(id), GoodsAttribute.class);

            attributeApplication.disable(attribute);
            logApplication.eventOfMerchant(Securitys.currentUser(), "禁用商品规格", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }


    }


    /**
     * 删除规格
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsAttribute attribute = queryChannelService.findOne(QGoodsAttribute.goodsAttribute.id.eq(id), GoodsAttribute.class);

            attributeApplication.remove(attribute);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除平台规格", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            return ImmutableMap.of("status", false, "message", "该规格已被使用，不允许删除");
        }


    }

    /**
     * 条件筛选
     *
     * @param sql
     * @param params
     * @param attribute
     * @return
     */
    private String builderSQL(String sql, Map<String, Object> params, GoodsAttribute attribute) {

        if (!Strings.isNullOrEmpty(attribute.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + attribute.getName() + "%");
        }

        return sql;
    }


}
